package com.lcredu.sqlSeesion;

import com.lcredu.entity.Monster;
import org.apache.ibatis.session.SqlSession;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author 黎长容
 * @date 2025-07-28 19:20
 */
public class LcrExecutor implements Executor {
    private LcrConfiguration lcrConfiguration = new LcrConfiguration();

    @Override
    public <T> T queryById(String sql, Object parameter) {
        System.out.println(parameter.toString());
        Connection connection = getConnection();
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, parameter.toString());
            resultSet = preparedStatement.executeQuery();
            Monster monster = new Monster();
            //这里使用反射,但是简化
            while (resultSet.next()) {
                monster.setId(resultSet.getInt("id"));
                monster.setAge(resultSet.getInt("age"));
                monster.setBirthday(resultSet.getDate("birthday"));
                monster.setEmail(resultSet.getString("email"));
                monster.setGender(resultSet.getInt("gender"));
                monster.setName(resultSet.getString("name"));
                monster.setSalary(resultSet.getDouble("salary"));
            }

            return (T) monster;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (resultSet != null) {
                    resultSet.close();
                }
                if (preparedStatement != null) {
                    preparedStatement.close();
                }

                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        //获取连接
        
    }


    public Connection getConnection() {
        return lcrConfiguration.build("lcr_mybatis.xml");
    }
}
